import React from 'react';
import {connect} from 'dva/index';
import {Button, Checkbox, Col, Form, Input, InputNumber, message, Row, Select, Table} from 'antd';
import Constants from '../../utils/Constants';
import RightConstants from '../../utils/RightConstants';
import RightBox from '../../components/common/rightBox';
import StreetSelect from '../../components/common/streetSelect';
import PortSelect from '../../components/common/portSelect';
import QuotationFeeDetail from '../../components/quotation/quotationFee/quotationFeeDetail';
import QuotationLocalFeeDetail from '../../components/quotation/quotationFee/quotationLocalFeeDetail'

const R = require('ramda');
const FormItem = Form.Item;
const InputGroup = Input.Group;
const { Option, OptGroup } = Select;
const CheckboxGroup = Checkbox.Group;

const labelStyle = {
    lineHeight: 2.5,
    borderTop: '1px solid #d9d9d9',
    borderBottom: '1px solid #d9d9d9',
    borderLeft: '1px solid #d9d9d9',
    width: 50,
    textAlign: 'center'
}

const quotationFee = Form.create()(class QuotationFee extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            lastSearchConditon: {}
        }
    }

    componentDidMount() {
        this.props.dispatch({ type: 'quotationFee/getQuotationListForPage', payload: { page: Constants.DEFAULT_PAGE, type: "1" } });
        this.props.dispatch({ type: 'berthingCompany/getAllBerthingCompanys' }); //查询船公司
    }

    handleOpen = (id, loadingId, destinationId, disabled) => {
        this.props.dispatch({
            type: 'currencyRate/getCnyByCurrent',
            payload: {
                currency: "USD"
            }
        })
        this.props.dispatch({
            type: 'quotationFee/refreshState',
            payload: {
                dataSource: {}
            }
        })
        this.quotationFeeDetail.handleOpen(null, id, loadingId, destinationId, null, null, null, disabled);
    }

    handleOpenLocal = (record, source) => {
        this.props.dispatch({
            type: 'quotationFee/getLocalFeeDetail',
            payload: {
                freightId: record.id,
                ...this.state.lastSearchConditon
            }
        });
        this.quotationLocalFeeDetail.handleOpen(record, source);
    }

    handleSearch = flag => {
        let newPage = this.props.quotationFee.page;
        if (flag) newPage.page = 1;
        let values = this.props.form.getFieldsValue();
        values.declare = values.service && (values.service.includes('1')) ? "1" : undefined;
        values.trailer = values.service && (values.service.includes('2')) ? "1" : undefined;
        values.insurance = values.service && (values.service.includes('3')) ? "1" : undefined;
        values.province = values.area && values.area[0] ? values.area[0] : "";
        values.city = values.area && values.area[1] ? values.area[1] : "";
        values.district = values.area && values.area[2] ? values.area[2] : "";
        values.street = values.area && values.area[3] ? values.area[3] : "";

        if (values.trailer == "1" && (R.isNil(values.area))) {
            message.error("请选择装柜地址！");
            return
        }

        if (values.insurance == "1" && (R.isNil(values.insuranceAmt))) {
            message.error("请输入货运保险货值！");
            return
        }
        this.setState({ lastSearchConditon: values });
        this.props.dispatch({
            type: 'quotationFee/getQuotationListForPage',
            payload: {
                ...values,
                page: newPage
            }
        });
    };

    columns = [
        {
            title: '起运港/目的港', key: 'port',
            render: record => {
                return <span>{record.loadingEnName}({record.loadingName})—>
                <div>{record.destinationEnName}({record.destinationName})</div></span>
            }
        },
        { title: '航线名称', dataIndex: 'airlineName', key: 'airlineName' },
        { title: '船公司代码', dataIndex: 'berthingCode', key: 'berthingCode' },
        { title: '船期', dataIndex: 'cut_off', key: 'cut_off' },
        { title: '航程(天数)', dataIndex: 'sail', key: 'sail' },
        {
            title: '中转港',
            render: record => {
                let view = <span>{record.transitEnName}({record.transitName})</span>;
                return (record.transitEnName ? view : null);
            }
        },
        { title: '20GP', dataIndex: 'fee20gp', key: 'fee20gp' },
        { title: '40GP', dataIndex: 'fee40gp', key: 'fee40gp' },
        { title: '40HQ', dataIndex: 'fee40hq', key: 'fee40hq' },
        {
            title: '附加费用', key: 'totalFee',
            render: record => {
                return <span><a href="#" onClick={this.handleOpenLocal.bind(this, record)}>本地费</a></span>
            }
        },
        //{ title: '运价备注', dataIndex: 'memo', key: 'memo' },
        {
            title: '有效期', key: 'date',
            render: record => {
                return <span>{record.begindate} 至 {record.enddate} </span>
            }
        },
        { title: '创建时间', dataIndex: 'createtime', key: 'createtime' },
        {
            title: '操作',
            render: (record) => {
                let viewLink = <RightBox resource={RightConstants.QUOTATION.QUOTATION_QUOTATIONFEE_EDIT} split={true}><a href="#" onClick={this.handleOpenLocal.bind(this, record, "1")}>明细</a></RightBox>
                let editLink = <RightBox resource={RightConstants.QUOTATION.QUOTATION_QUOTATIONFEE_EDIT}><a href="#" onClick={this.handleOpen.bind(this, record.id, record.loadingId, record.destinationId, false)}>报价</a></RightBox>
                return <span>{viewLink}{editLink}</span>
            }
        }
    ];

    render() {
        let formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 16 } };
        let checkboxLayout = { labelCol: { span: 10 }, wrapperCol: { span: 14 } };
        let berthingCompanyList = this.props.berthingCompany.berthingCompanyList ? this.props.berthingCompany.berthingCompanyList : [];
        let areaStreetTree = this.props.app.areaStreetTree ? this.props.app.areaStreetTree : [];
        const { getFieldDecorator } = this.props.form;
        let pagination = {
            showTotal: total => `共 ${total} 条数据`,
            current: this.props.quotationFee.page.page,
            pageSize: this.props.quotationFee.page.size,
            total: this.props.quotationFee.page.totalRow,
            showSizeChanger: true,
            onShowSizeChange: (current, size) => {
                let newPage = this.props.quotationFee.page;
                newPage.size = size;
                newPage.page = 1;
                this.props.dispatch({
                    type: 'quotationFee/getQuotationListForPage',
                    payload: {
                        ...this.props.form.getFieldsValue(),
                        page: newPage
                    }
                });
            },
            onChange: (pageNumber, pageSize) => {
                let newPage = this.props.quotationFee.page;
                newPage.page = pageNumber;
                this.props.dispatch({
                    type: 'quotationFee/getQuotationListForPage',
                    payload: {
                        ...this.props.form.getFieldsValue(),
                        page: newPage
                    }
                });
            }
        }

        let trailerAddress =
            <div>
                <Row>
                    <Col span={17} style={{ marginLeft: 10 }}>
                        <FormItem {...formItemLayout} label="装柜地址">{getFieldDecorator('area')(
                            <StreetSelect style={{ width: '100%' }} allowClear />
                        )}
                        </FormItem>
                    </Col>
                </Row>
            </div>

        let insuranceValue =
            <div>
                <Col span={6}>
                    <FormItem {...formItemLayout} label={'保险货值'}>
                        {getFieldDecorator('insuranceAmt')(
                            <InputNumber min={0} maxLength="18" placeholder="货运保险货值" style={{ width: '100%' }} />)}
                    </FormItem>
                </Col>
                <Col span={5}>
                    {getFieldDecorator('insuranceCcy', {
                        initialValue: "1"
                    })(
                        <Select size="large" style={{ width: '40%' }} allowClear>
                            <Select.Option value="1">CNY</Select.Option>
                            <Select.Option value="2">USD</Select.Option>
                        </Select>
                        )}
                </Col>
            </div>

        return (
            <div>
                <Row>
                    <InputGroup compact style={{ marginLeft: 300, marginTop: 20 }} size="large">
                        {getFieldDecorator('type', {
                            initialValue: "1"
                        })(
                            <Select style={{ width: '8%' }} allowClear>
                                <Select.Option value="1">整柜</Select.Option>
                                <Select.Option value="2">拼柜</Select.Option>
                                <Select.Option value="3">拖车</Select.Option>
                                <Select.Option value="4">空运</Select.Option>
                                <Select.Option value="5">快递</Select.Option>
                            </Select>
                            )}

                        <span style={labelStyle}>起运港</span>
                        {getFieldDecorator('loadingPort')(
                            <PortSelect style={{ width: '13%' }} portType={"1"} allowClear />
                        )}

                        <span style={labelStyle}>目的港</span>
                        {getFieldDecorator('destinationPort')(
                            <PortSelect style={{ width: '13%' }} portType={"1"} allowClear />
                        )}

                        <span style={labelStyle}>船公司</span>
                        {getFieldDecorator('berthingId')(
                            <Select style={{ width: '13%' }} showSearch allowClear
                                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
                                {
                                    !R.isNil(berthingCompanyList) ? berthingCompanyList.map(item => {
                                        return (<Select.Option value={item.id + ""} key={item.id + ""}>{item.berthingCode}</Select.Option>);
                                    }) : ''
                                }
                            </Select>
                        )}
                        <Button type="primary" icon="search" size="large" onClick={this.handleSearch.bind(this, true)}>查询</Button>
                    </InputGroup>
                </Row>

                {['1'].includes(this.props.form.getFieldValue('type')) ?
                    <Row style={{ marginLeft: 135, marginTop: 20 }}>
                        <Col span={10}>
                            <FormItem {...checkboxLayout} label={'增值服务'}>
                                {getFieldDecorator('service')(
                                    <CheckboxGroup style={{ width: 800 }}>
                                        <Checkbox value="1">报关服务</Checkbox>
                                        <Checkbox value="2">拖车服务</Checkbox>
                                        <Checkbox value="3">货运保险<span style={{ color: 'red' }}>费率0.1%</span></Checkbox>
                                    </CheckboxGroup>
                                )}
                            </FormItem>
                        </Col>
                        {this.props.form.getFieldValue('service') && (this.props.form.getFieldValue('service').includes('3')) ?
                            insuranceValue
                            : ""
                        }
                    </Row>
                    : ""}

                {this.props.form.getFieldValue('service') && (this.props.form.getFieldValue('service').includes('2')) ?
                    trailerAddress
                    : ""
                }
                <Table
                    rowKey='id'
                    loading={this.props.loading}
                    columns={this.columns}
                    dataSource={this.props.form.getFieldValue("type") == "1" ? this.props.quotationFee.list : []}
                    bordered={true} size={'middle'}
                    title={() => <span style={{ color: 'red' }}>*注：如无特殊说明以下海运费币种均以USD为准</span>}
                    pagination={pagination} 
                    style={{ marginTop: 20 }}/>
                <QuotationFeeDetail wrappedComponentRef={(inst) => this.quotationFeeDetail = inst} refreshList={this.handleSearch} lastSearchConditon={this.state.lastSearchConditon} />
                <QuotationLocalFeeDetail wrappedComponentRef={(inst) => this.quotationLocalFeeDetail = inst} refreshList={this.handleSearch} lastSearchConditon={this.state.lastSearchConditon} />
            </div>
        )
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.quotationFee, quotationFee: state.quotationFee, berthingCompany: state.berthingCompany, app: state.app
    };
}

export default connect(mapStateToProps)(quotationFee);